/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package kale.ui.component;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.element.ShapeElement;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

/**
 * HmButton
 *
 * @author AnBetter
 * @since 2021-06-01
 */
public class HmButton extends Button implements Component.TouchEventListener {
    private float mRadius;
    private int downColor;
    private int upColor;

    /** 构造
     *
     * @param context
     */
    public HmButton(Context context) {
        super(context);
    }

    /** 构造
     *
     * @param context
     * @param attrSet
     */
    public HmButton(Context context, AttrSet attrSet) {
        super(context, attrSet);
        mRadius = attrSet.getAttr("radius").get().getFloatValue();
        downColor = attrSet.getAttr("DownColor").get().getIntegerValue();
        upColor = attrSet.getAttr("UpColor").get().getIntegerValue();
        ShapeElement element = new ShapeElement();
        this.setBackground(initShapeElement(mRadius, upColor));
        this.setTouchEventListener(this::onTouchEvent);
    }

    /** 构造
     *
     * @param context
     * @param attrSet
     * @param styleName
     */
    public HmButton(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    private ShapeElement initShapeElement(float radius, int color) {
        ShapeElement element = new ShapeElement();
        element.setCornerRadius(radius);
        int color1 = color;
        element.setRgbColor(RgbColor.fromArgbInt(color1));
        return element;
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        switch (touchEvent.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                this.setBackground(initShapeElement(mRadius, downColor));
                return true;
            case TouchEvent.PRIMARY_POINT_UP:
                this.setBackground(initShapeElement(mRadius, upColor));
                return true;
            default:
                break;
        }
        return false;
    }
}
